package com.woniu.zsd.merchant.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.woniu.client.PermissionClient;
import com.woniu.client.UserClient;
import com.woniu.dto.QueryToInfoDto;
import com.woniu.dto.UserDto;
import com.woniu.form.ChatMessage;
import com.woniu.zsd.merchant.entity.ChatHistory;
import com.woniu.zsd.merchant.mapper.ChatHistoryMapper;
import com.woniu.zsd.merchant.service.IChatHistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.commons.util.RedisKey;
import com.woniu.zsd.merchant.util.MerchartTokenUtil;
import com.woniu.zsd.permission.entity.AdminInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-03-27
 */
@Service
public class ChatHistoryServiceImpl extends ServiceImpl<ChatHistoryMapper, ChatHistory> implements IChatHistoryService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MerchartTokenUtil tokenUtil;
    @Autowired
    private PermissionClient permissionClient;
    @Autowired
    private UserClient userClient;

    @Override
    public List<ChatMessage> getChatHistory(String form, String to) {
        // 判断form的角色是管理员还是用户
        String userId = null;
        String adminId = null;
        if (stringRedisTemplate.hasKey(RedisKey.USER_REFRESH_TOKEN_KEY(form))){
            userId = tokenUtil.getUserId(form).toString();
        } else {
            adminId = tokenUtil.getAdminId(form).toString();
        }
        if (userId!=null) {
            adminId = to;
        } else {
            userId = to;
        }

        // 获取两方的聊天记录键
        String userAdminKey = RedisKey.TALK_USER_ADMIN_KEY(userId, adminId);
        String adminUserKey = RedisKey.TALK_ADMIN_USER_KEY(userId, adminId);

        Set<String> formToMessages = stringRedisTemplate.opsForZSet().range(userAdminKey, 0, -1);
        System.out.println(formToMessages);
        Set<String> toFormMessages = stringRedisTemplate.opsForZSet().range(adminUserKey, 0, -1);
        System.out.println(toFormMessages);

        // 初始化TreeSet并指定比较器
        Set<String> allMessages = new TreeSet<>(Comparator.comparingLong(o -> {
            JSONObject jsonObject = JSONUtil.parseObj(o);
            Long time = parseTime(jsonObject.getStr("time"));
            return time != null ? time : System.currentTimeMillis();
        }));

        // 添加消息到集合中
        if (formToMessages != null && !formToMessages.isEmpty()) {
            allMessages.addAll(formToMessages);
        }
        if (toFormMessages != null && !toFormMessages.isEmpty()) {
            allMessages.addAll(toFormMessages);
        }

        // 转换为ChatMessage对象列表
        List<ChatMessage> chatMessages = new ArrayList<>();
        for (String msgStr : allMessages) {
            ChatMessage chatMessage = JSONUtil.toBean(JSONUtil.parseObj(msgStr), ChatMessage.class);
            chatMessages.add(chatMessage);
        }

        // 清空未读消息计数和列表
        String unreadCountKey = RedisKey.UNREAD_MESSAGE_COUNT_KEY(userId, adminId);
        String unreadListKey = RedisKey.UNREAD_MESSAGE_LIST_KEY(userId, adminId);

        stringRedisTemplate.delete(unreadCountKey);
        stringRedisTemplate.delete(unreadListKey);

        return chatMessages;
    }

    @Override
    public List<QueryToInfoDto> queryToInfo(String token) {
        List<QueryToInfoDto> queryToInfoDto = new ArrayList<>();
        Set<String> userInfo = null;
        Set<String> adminInfo = null;
        // 判断token是管理员还是用户
        String userId = null;
        String adminId = null;
        if (stringRedisTemplate.hasKey(RedisKey.USER_REFRESH_TOKEN_KEY(token))){
            userId = tokenUtil.getUserId(token).toString();
        } else {
            adminId = tokenUtil.getAdminId(token).toString();
        }
        //如果是用户说明存储的是管理员ID
        if (userId!=null){
            adminInfo = stringRedisTemplate.opsForZSet().range(RedisKey.TALK_FORM_USER_KEY(userId), 0, -1);
            Set<Integer> adminIds = new HashSet<>();
            if (adminInfo != null) {
                for (String id : adminInfo) {
                    adminIds.add(Integer.parseInt(id));
                }
            }
            List<AdminInfo> adminInfos = permissionClient.selectAdminInfoByIds(adminIds).getData();
            if (adminInfos != null) {
                for (AdminInfo admin : adminInfos) {
                    QueryToInfoDto queryToAdminInfoDto = new QueryToInfoDto();
                    queryToAdminInfoDto.setId(admin.getAdminId());
                    queryToAdminInfoDto.setNickName(admin.getName());
                    queryToAdminInfoDto.setHeadPath(admin.getHeadPath());
                    queryToAdminInfoDto.setToType("admin");
                    queryToInfoDto.add(queryToAdminInfoDto);
                }
            }
        }else { //如果是管理员说明存储的是用户ID
            userInfo = stringRedisTemplate.opsForZSet().range(RedisKey.TALK_FORM_ADMIN_KEY(adminId), 0, -1);
            // 将Set<String>转换为Set<Integer>
            Set<Integer> userIds = new HashSet<>();
            if (userInfo != null) {
                for (String id : userInfo) {
                    userIds.add(Integer.parseInt(id));
                }
            }
            List<UserDto> userDtos = userClient.selUserInfoByIds(userIds).getData();
            System.out.println(userDtos);
            if (userDtos != null) {
                for (UserDto userDto : userDtos){
                    QueryToInfoDto queryToUserInfoDto = new QueryToInfoDto();
                    queryToUserInfoDto.setId(userDto.getId());
                    queryToUserInfoDto.setNickName(userDto.getNickName());
                    queryToUserInfoDto.setHeadPath(userDto.getHeadImage());
                    queryToUserInfoDto.setToType("user");
                    queryToInfoDto.add(queryToUserInfoDto);
                    System.out.println(queryToUserInfoDto);
                }
            }
        }

        return queryToInfoDto;
    }

    private Long parseTime(String timeStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(timeStr);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}
